import requests

# 替换为你的高德API Key
API_KEY = "f981486457ce2b599895542094ac9104"


class AMapSubwayPlanner:
    def __init__(self, api_key=API_KEY):
        self.api_key = api_key

    def get_coordinates(self, address, city="北京"):
        """将地址转换为高德坐标"""
        url = "https://restapi.amap.com/v3/geocode/geo"
        params = {"key": self.api_key, "address": address, "city": city}

        try:
            response = requests.get(url, params=params)
            data = response.json()
            if data["status"] == "1" and data["geocodes"]:
                return data["geocodes"][0]["location"]
            print(f"地址解析失败: {data.get('info', '未知错误')}")
            return None
        except Exception as e:
            print(f"坐标获取出错: {e}")
            return None

    def get_subway_route(self, origin, destination, city="北京"):
        """获取地铁路径规划"""
        base_url = "https://restapi.amap.com/v3/direction/transit/integrated"

        params = {
            "key": self.api_key,
            "origin": origin,
            "destination": destination,
            "city": city,
            "strategy": 2,  # 优先选择最少换乘
            "extensions": "base",
        }

        try:
            response = requests.get(base_url, params=params)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"路径规划请求出错: {e}")
            return None

    def format_duration(self, seconds):
        """将秒数格式化为小时分钟"""
        minutes = int(seconds) // 60
        if minutes < 60:
            return f"{minutes}分钟"
        else:
            return f"{minutes // 60}小时{minutes % 60}分钟"

    def get_location_name(self, location):
        """将坐标转换为地点名称"""
        url = "https://restapi.amap.com/v3/geocode/regeo"
        params = {"key": self.api_key, "location": location}

        response = requests.get(url, params=params)
        data = response.json()
        if data["status"] == "1" and data["regeocode"]:
            return data["regeocode"]["formatted_address"]
        return location  # 如果转换失败，返回原始坐标

    def print_route(self, route_data):
        """打印路径规划结果"""
        if not route_data or route_data.get("status") != "1":
            print("路径规划失败:", route_data.get("info", "未知错误"))
            return

        routes = route_data.get("route", {}).get("transits", [])
        if not routes:
            print("未找到合适的公共交通路线")
            return

        print("\n=== 地铁路径规划结果 ===")

        for i, route in enumerate(routes[:3], 1):  # 只显示前3个方案
            print(f"\n方案 {i}:")
            print(f"预计耗时: {self.format_duration(route['duration'])}")
            print(f"总步行距离: {route['walking_distance']}米")
            print(f"预计票价: {route['cost']}元")

            print("\n路线详情:")
            # 先收集所有地铁段和公交段
            subway_segments = []
            bus_segments = []
            walking_segments = []

            for segment in route["segments"]:
                if segment.get("railway") and segment["railway"].get("via_stops"):
                    subway_segments.append(segment)
                elif segment.get("bus") and segment["bus"].get("buslines"):
                    busline = segment["bus"]["buslines"][0]
                    if "地铁" in busline.get("type", "") or "地铁" in busline.get(
                        "name", ""
                    ):
                        subway_segments.append(segment)
                    else:
                        bus_segments.append(segment)
                if segment.get("walking"):
                    walking_segments.append(segment)

            # 按顺序打印所有段落
            all_segments = route["segments"]
            for segment in all_segments:
                # 优先处理地铁和公交
                if segment.get("bus") and segment["bus"].get("buslines"):
                    busline = segment["bus"]["buslines"][0]
                    line_type = (
                        "🚇"
                        if "地铁" in busline.get("type", "")
                        or "地铁" in busline.get("name", "")
                        else "🚌"
                    )

                    departure = busline["departure_stop"]["name"]
                    arrival = busline["arrival_stop"]["name"]

                    print(
                        f"{line_type} 乘坐 {busline['name']} (共{busline['via_num']}站, {self.format_duration(busline['duration'])})"
                    )
                    print(f"  上车: {departure}")

                    # 如果有经过站，打印经过站
                    if int(busline.get("via_num", 0)) > 0 and busline.get("via_stops"):
                        via_stops = [stop["name"] for stop in busline["via_stops"]]
                        print(f"  经过: {' → '.join(via_stops)}")

                    print(f"  下车: {arrival}")

                    if busline.get("start_time") and busline.get("end_time"):
                        print(
                            f"  首班车: {busline['start_time']} 末班车: {busline['end_time']}"
                        )

                # 处理步行段
                elif segment.get("walking"):
                    walk = segment["walking"]
                    print(
                        f"🚶 步行 {walk['distance']}米 ({self.format_duration(walk['duration'])})"
                    )

                    if "origin" in walk:
                        origin = walk["origin"]
                        if isinstance(origin, dict) and "name" in origin:
                            print(f"  从 {origin['name']} 出发")
                        else:
                            location_name = self.get_location_name(origin)
                            print(f"  从 {location_name} 出发")

                    if "destination" in walk:
                        dest = walk["destination"]
                        if isinstance(dest, dict) and "name" in dest:
                            print(f"  到达 {dest['name']}")
                        else:
                            location_name = self.get_location_name(dest)
                            print(f"  到达 {location_name}")

                    # 如果有步行指引steps，可以考虑打印
                    if "steps" in walk and walk["steps"]:
                        for step in walk["steps"]:
                            if (
                                step.get("assistant_action")
                                and step["assistant_action"] != "[]"
                            ):
                                print(f"  {step['assistant_action']}")

            print("-" * 50)

    def get_route_summary(self, route_data):
        """生成路径的简短描述，适合语音播报"""
        if not route_data or route_data.get("status") != "1":
            return "抱歉，没有找到合适的路径。"

        routes = route_data.get("route", {}).get("transits", [])
        if not routes:
            return "抱歉，没有找到合适的公共交通路线。"

        # 选择第一个方案
        route = routes[0]

        total_time = self.format_duration(route["duration"])
        total_walk = route["walking_distance"]
        cost = route["cost"]

        # 收集主要交通方式
        transport_methods = []
        stations = []

        for segment in route["segments"]:
            if segment.get("bus") and segment["bus"].get("buslines"):
                busline = segment["bus"]["buslines"][0]
                if "地铁" in busline.get("type", "") or "地铁" in busline.get(
                    "name", ""
                ):
                    line_name = busline["name"].split("(")[
                        0
                    ]  # 提取线路名称，去除括号内内容
                    transport_methods.append(f"{line_name}")
                    # 记录起点和终点站
                    stations.append(busline["departure_stop"]["name"])
                    stations.append(busline["arrival_stop"]["name"])

        # 移除重复站点（换乘时的重复站）
        unique_stations = []
        for station in stations:
            if not unique_stations or station != unique_stations[-1]:
                unique_stations.append(station)

        # 构建简短描述
        transport_summary = (
            "、".join(transport_methods) if transport_methods else "步行"
        )

        if unique_stations:
            station_summary = f"从{unique_stations[0]}出发，到达{unique_stations[-1]}"
            middle_stations = unique_stations[1:-1]
            if middle_stations:
                station_summary += f"，途经{len(middle_stations)}个站点"
        else:
            station_summary = ""

        summary = f"预计耗时{total_time}，需步行{total_walk}米，票价{cost}元。"

        if transport_methods:
            return f"建议乘坐{transport_summary}。{station_summary}。{summary}"
        else:
            return f"建议全程步行。{summary}"


def main():
    planner = AMapSubwayPlanner()

    print("=== 高德地铁路径规划 ===")
    # city = input("请输入城市名称(如: 北京): ").strip()
    # start_addr = input("请输入起点地址(如: 北京西站): ").strip()
    # end_addr = input("请输入目的地地址(如: 北京南站): ").strip()
    city = "北京"

    start_addr = "知春路地铁站"
    end_addr = "枣园地铁站"

    print("\n正在查询路线...")

    # 获取坐标
    start_loc = planner.get_coordinates(start_addr, city)
    end_loc = planner.get_coordinates(end_addr, city)

    if not start_loc or not end_loc:
        print("地址解析失败，请检查输入是否正确")
        return

    # 获取路径规划
    route_data = planner.get_subway_route(start_loc, end_loc, city)

    # 打印结果
    planner.print_route(route_data)

    summary = planner.get_route_summary(route_data)
    print(summary)


if __name__ == "__main__":
    main()